﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using SevenZip;
using System.Text.RegularExpressions;
using System.Threading;
using Client;
using SeniorCapstoneProject.ServiceReference3;
using System.Xml.Serialization;
using System.Xml;

namespace SeniorCapstoneProject
{
    delegate void UpdateCompressionInvoker(string name);
    delegate void UpdateMessageInvoker(string name);
    delegate void pgBar_Update(long BytesRead, long BytesLength, string fileName);
    delegate void trvLocalUpdate(string newFileName);

    public partial class frmMain : Form
    {
        private int i = 2;
        private List<TabPage> _HiddenPages = new List<TabPage>();
        private List<Label> _ActiveUpload = new List<Label>();
        private List<ProgressBar> _ProgressBars = new List<ProgressBar>();
        private List<Label> _ActiveDownload = new List<Label>();
        private List<TreeNode> AdminTreeNodes = new List<TreeNode>();
        public verifyUser uLogin = new verifyUser();
        private List<FileInformation> fim = new List<FileInformation>();
        public List<Thread> threadStore = new List<Thread>();
        public List<ManualResetEvent> threadActivity = new List<ManualResetEvent>();
        public List<ManualResetEvent> threadTransfer = new List<ManualResetEvent>();
        public List<FileStatus> fileContinuation = new List<FileStatus>();
        public List<string> downloadArray = new List<string>();
        private int contFile = -1;
        private string downloadStatusString;
        private int threadCont = 0;

        public frmMain() { }

        public frmMain(verifyUser uLogin)
        {
            InitializeComponent();
            this.uLogin = uLogin;
            TreeNode node = trvLocal.Nodes.Add("Local Files");
            List<string> localList = new List<string>(Properties.FileSettings.Default.FileLocations.Split(';'));

            foreach(string local in localList)
            {
                if (local.Length > 0)
                {
                    node.Nodes.Add(Path.GetFileName(local));
                }
            }

            refreshRemoteFile();

            if (uLogin.groupID == 1)
            {
                cmbAdminTools.Visible = true;
            }
            else
            {
                cmbAdminTools.Visible = false;
            }

            trvRemote.ExpandAll();
            trvLocal.ExpandAll();
            UpdateMessageBoard("Connected as user: " + uLogin.Username);
        }

        private void refreshRemoteFile()
        {
            trvRemote.Nodes.Clear();
            AdminTreeNodes = new List<TreeNode>();
            TransferFilesClient tfc = new TransferFilesClient();
            List<FileInformation> fim = new List<FileInformation>();
            
            uLogin.groupID =  tfc.AuthUser(uLogin.Username, uLogin.Password);

            var gl = tfc.GetList(uLogin.Username, uLogin.Password, uLogin.groupID);

            foreach (ServiceReference3.FileInformation trial in gl)
            {
                FileInformation fi = new FileInformation();
                fi.FileName = trial.Path;
                fi.Permissions = trial.Permissions;
                fi.GroupID = trial.GroupID;
                fi.GroupName = trial.GroupName;
                fi.UserGroupID = trial.uGroupID;
                fi.Size = trial.Size;
                fim.Add(fi);
            }
            this.fim = fim;

            List<ServiceReference3.HelperClass> temp = tfc.GetGroups().ToList<ServiceReference3.HelperClass>();

            if (uLogin.groupID == 1)
            {
                foreach (ServiceReference3.HelperClass trial in temp)
                {
                    TreeNode tTemp = new TreeNode();
                    tTemp.Name = trial.GroupName;
                    tTemp.Text = trial.GroupName;
                    AdminTreeNodes.Add(tTemp);
                }
            }
            else
            {
                foreach (ServiceReference3.HelperClass trial in temp)
                {
                    if (trial.GroupID == uLogin.groupID)
                    {
                        TreeNode tTemp = new TreeNode();
                        tTemp.Name = trial.GroupName;
                        tTemp.Text = trial.GroupName;
                        AdminTreeNodes.Add(tTemp);
                        break;
                    }
                }
            }
            
            TreeNode node = trvRemote.Nodes.Add("Remote Files");

            foreach (TreeNode tNode in AdminTreeNodes)
            {
                node.Nodes.Add(tNode);
            }

            for (int i = 0; i < fim.Count(); i++)
            {
                foreach (TreeNode tNode in AdminTreeNodes)
                {
                    if (fim[i].GroupName == tNode.Name)
                    {
                        tNode.Nodes.Add(Path.GetFileName(fim[i].FileName));
                    }
                }
            }
            trvRemote.ExpandAll();
        }

        private void btnDownload_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
            ToolTip tt = new ToolTip();
            tt.SetToolTip(this.btnDownload, "Download file from remote server.");
        }

        private void btnUpload_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
            ToolTip tt = new ToolTip();
            tt.SetToolTip(this.btnUpload, "Send file to remote server.");
        }

        private void btnLocalRemove_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
            ToolTip tt = new ToolTip();
            tt.SetToolTip(this.btnLocalRemove, "Remove file from list.");
        }

        private void btnLocalAdd_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
            ToolTip tt = new ToolTip();
            tt.SetToolTip(this.btnLocalAdd, "Add file to the list.");
        }

        private void mouse_Hover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btnsLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Default;
        }

        public void trvLocalUpdate(string newFileName)
        {
            trvLocal.Nodes[0].Nodes.Add(Path.GetFileName(newFileName.ToString()));
            trvLocal.ExpandAll();
        }

        private void btnLocalAdd_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                trvLocal.Nodes[0].Nodes.Add(Path.GetFileName(openFile.FileName.ToString()));
                UpdateMessageBoard("Added file to project: " + openFile.FileName.ToString());
                Properties.FileSettings.Default.FileLocations = Properties.FileSettings.Default.FileLocations + openFile.FileName.ToString() + ";";
                Properties.FileSettings.Default.Save();
                trvLocal.ExpandAll();
            }
        }

        private void btnLocalRemove_Click(object sender, EventArgs e)
        {
            try
            {
                if (trvLocal.SelectedNode.Parent != null)
                {
                    DialogResult drm = customMessage("Confirm?", "Remove file from project?", "Are you sure you want to remove " + trvLocal.SelectedNode.Text + "?", "OK", "Cancel");
                    if (drm == DialogResult.Yes)
                    {
                        string[] words = Properties.FileSettings.Default.FileLocations.Split(';');
                        string newProp = "";
                        foreach (string word in words)
                        {
                            if (Path.GetFileName(word) != (trvLocal.SelectedNode.Text) && word.Length > 0)
                            {
                                newProp += word + ";";
                            }
                            else if (word.Length > 0)
                            {
                                UpdateMessageBoard("File removed: " + trvLocal.SelectedNode.Text);
                            }
                        }
                        trvLocal.Nodes.Remove(trvLocal.SelectedNode);
                        Properties.FileSettings.Default.FileLocations = newProp;
                        Properties.FileSettings.Default.Save();
                    }
                }
                else
                {
                    customMessage("Error!!!", "Can't find selected file", "You must select a file from the list.", "OK", null);
                    UpdateMessageBoard("You must select a file to remove.");
                }
            }
            catch
            {
                customMessage("Error!!!", "Can't find selected file", "You must select a file from the list.", "OK", null);
                UpdateMessageBoard("You must select a file to remove.");
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            try
            {
                if (AdminTreeNodes.Count() == 1 || trvRemote.SelectedNode.Parent.Text == "Remote Files")
                {
                    if (trvLocal.SelectedNode.Parent != null)
                    {
                        bool active = false;
                        foreach (Label checkLabel in _ActiveUpload)
                        {
                            if (checkLabel.Text == trvLocal.SelectedNode.Text)
                            {
                                active = true;
                            }
                        }
                        if (active == false)
                        {
                            CreateTabUpload(0);

                            FileSpliterJoiner fsj = new FileSpliterJoiner();
                            string[] words = Properties.FileSettings.Default.FileLocations.Split(';');
                            foreach (string word in words)
                            {
                                if (Path.GetFileName(word) == (trvLocal.SelectedNode.Text) && word.Length > 0)
                                {
                                    if (AdminTreeNodes.Count > 1)
                                    {
                                        fsj.BeginSplitFiles(word, this, uLogin, trvRemote.SelectedNode.Text, threadActivity.Count - 1);
                                        break;
                                    }
                                    else
                                    {
                                        fsj.BeginSplitFiles(word, this, uLogin, AdminTreeNodes[0].Text.ToString(), threadActivity.Count - 1);
                                        break;
                                    }
                                }
                            }
                            UpdateMessageBoard("Started uploading file: " + trvLocal.SelectedNode.Text);
                            tabControl1.SelectedTab = tabStatus;
                        }
                        else
                        {
                            customMessage("Warning", "Upload already in progress", "File: " + trvLocal.SelectedNode.Text + " is already being sent to the server", "OK", null);
                        }
                    }
                    else
                    {
                        customMessage("Error!!!", "Can't find selected file", "You must select a file to start transfering.", "OK", null);
                        UpdateMessageBoard("You must select a file to start transfering.");
                    }
                }
                else
                {
                    customMessage("Error!!!", "No group selected", "You must select a group from the remote tree.", "OK", null);
                    UpdateMessageBoard("You must select a group to transfer to.");
                }
            }
            catch (NullReferenceException ex)
            {
                customMessage("Error!!!", "No group selected", "You must select a group from the remote tree.", "OK", null);
                UpdateMessageBoard("You must select a group to transfer to.");
            }
            catch (Exception ex)
            {
                customMessage("Error!!!", "Can't find selected file", "You must select a file to start transfering.", "OK", null);
                UpdateMessageBoard("You must select a file to start transfering.");
            }
        }

        public int m = 0;

        private void CreateTabUpload(int k)
        {
            string tabProperties = Path.GetFileNameWithoutExtension(trvLocal.SelectedNode.Text);
            TabPage newPage = new System.Windows.Forms.TabPage();
            TableLayoutPanel tlpProperties = new TableLayoutPanel();
            Panel pnl = new Panel();
            PictureBox pct = new PictureBox();
            Label cellLabel = new Label();
            ProgressBar pgBar = new ProgressBar();

            newPage.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
            newPage.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

            newPage.Controls.Add(tlpProperties); //Add table
            newPage.Controls.Add(pnl);

            newPage.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text)); //Set Page layout
            newPage.Padding = new System.Windows.Forms.Padding(3);
            newPage.Size = new System.Drawing.Size(613, 248);
            newPage.TabIndex = i;
            newPage.Text = tabProperties;
            _HiddenPages.Add(newPage);

            tlpProperties.ColumnCount = 4; //Create Columns
            tlpProperties.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 65F));
            tlpProperties.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
            tlpProperties.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
            tlpProperties.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 35F));

            SplitJoinCompress sjc = new SplitJoinCompress(null, null, null, null, 0); //retrieve file size
            int j = sjc.FileParts();
            string[] words = Properties.FileSettings.Default.FileLocations.Split(';');
            string newProp = "";
            foreach (string word in words)
            {
                if (Path.GetFileName(word) == (trvLocal.SelectedNode.Text))
                {
                    newProp = word;
                    break;
                }
            }
            FileInfo tempLookup = new FileInfo(newProp);
            m = Convert.ToInt32(Math.Ceiling((double)tempLookup.Length / j + 1));

            tlpProperties.RowCount = m + 2; //Create Rows
            for (int p = 0; p <= m; p++)
            {
                tlpProperties.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
            }

            //Set panel properties
            pnl.Dock = System.Windows.Forms.DockStyle.Top;
            pnl.Location = new System.Drawing.Point(3, 3);
            pnl.Size = new System.Drawing.Size(605, 21);
            pnl.Margin = new System.Windows.Forms.Padding(0, 3, 0, 3);
            tlpProperties.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
            tlpProperties.AutoScroll = true;

            //Add close button
            pct = new PictureBox();
            pct.Dock = DockStyle.Right;
            pct.Image = (Image)Properties.Resources.delete;
            pct.Location = new System.Drawing.Point(580, 3);
            pct.Name = "close" + i;
            pct.Size = new System.Drawing.Size(21, 21);
            pct.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            pct.TabIndex = 0;
            pct.TabStop = false;
            pct.Click += new EventHandler(close_Click);
            pnl.Controls.Add(pct);

            //Add Panel
            newPage.Controls.Add(pnl);

            //Add labels
            cellLabel = new Label();
            cellLabel.Text = "File Names";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleCenter;
            tlpProperties.Controls.Add(cellLabel, 0, 0);

            cellLabel = new Label();
            cellLabel.Text = "Compression";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleCenter;
            tlpProperties.Controls.Add(cellLabel, 1, 0);

            cellLabel = new Label();
            cellLabel.Text = "Transfer";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleCenter;
            tlpProperties.Controls.Add(cellLabel, 2, 0);

            cellLabel = new Label();
            cellLabel.Text = "Notes";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleCenter;
            tlpProperties.Controls.Add(cellLabel, 3, 0);

            //Add main file
            cellLabel = new Label();
            cellLabel.Text = Path.GetFileName(trvLocal.SelectedNode.Text);
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleLeft;
            tlpProperties.Controls.Add(cellLabel, 0, 1);

            //Add main file progress bars
            pgBar = new ProgressBar();
            pgBar.Dock = DockStyle.Fill;
            pgBar.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text)) + "_Compression";
            pgBar.Maximum = m;
            _ProgressBars.Add(pgBar);
            tlpProperties.Controls.Add(pgBar, 1, 1);

            pgBar = new ProgressBar();
            pgBar.Dock = DockStyle.Fill;
            pgBar.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text)) + "_Transfer";
            pgBar.Maximum = m;
            _ProgressBars.Add(pgBar);
            tlpProperties.Controls.Add(pgBar, 2, 1);

            //Add main file notes
            cellLabel = new Label();
            cellLabel.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text)) + "_Notes";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleLeft;
            tlpProperties.Controls.Add(cellLabel, 3, 1);

            //Add subfiles
            for (int p = 0; p < (m - 1); p++)
            {
                //Add sub file
                cellLabel = new Label();
                cellLabel.Text = "  - " + Path.GetFileName(trvLocal.SelectedNode.Text) + ".part" + p.ToString("0000");
                cellLabel.Dock = DockStyle.Fill;
                cellLabel.TextAlign = ContentAlignment.MiddleLeft;
                tlpProperties.Controls.Add(cellLabel, 0, p + 2);

                //Add sub file progress bars
                pgBar = new ProgressBar();
                pgBar.Dock = DockStyle.Fill;
                pgBar.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text) + "part" + p.ToString("0000")) + "_Compression";
                pgBar.Maximum = 3;
                _ProgressBars.Add(pgBar);
                tlpProperties.Controls.Add(pgBar, 1, p + 2);

                pgBar = new ProgressBar();
                pgBar.Dock = DockStyle.Fill;
                pgBar.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text) + "part" + p.ToString("0000")) + "_Transfer";
                _ProgressBars.Add(pgBar);
                tlpProperties.Controls.Add(pgBar, 2, p + 2);
                ManualResetEvent _suspendThread = new ManualResetEvent(true);
                threadTransfer.Add(_suspendThread);

                //Add sub file notes
                cellLabel = new Label();
                cellLabel.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text) + p.ToString("0000")) + "_Notes";
                cellLabel.Dock = DockStyle.Fill;
                cellLabel.TextAlign = ContentAlignment.MiddleLeft;
                tlpProperties.Controls.Add(cellLabel, 3, p + 2);
            }

            //Finish table properties
            tlpProperties.Dock = System.Windows.Forms.DockStyle.Fill;
            tlpProperties.Location = new System.Drawing.Point(3, 3);
            tlpProperties.Size = new System.Drawing.Size(607, 242);
            tlpProperties.TabIndex = 0;

            AddStatus(k);

            for (int o = 0 + threadCont; o < threadTransfer.Count; o++)
            {
                if (contFile != -1)
                {
                    if (o - threadCont == contFile)
                    {
                        pgBar_update(-2, -2, fileContinuation[threadActivity.Count - 1].FileName);

                        FileSendRecieve fsr = new FileSendRecieve();
                        SplitJoinCompress fsj = new SplitJoinCompress();

                        string fiSource = trvLocal.SelectedNode.Text;

                        double totalFileSize = (long)fiSource.Length; //Set total size of file
                        double tempParts = totalFileSize / fsj.FileParts();
                        int totalParts = Convert.ToInt32(Math.Ceiling(tempParts));

                        string testPath = Path.GetDirectoryName(fileContinuation[threadActivity.Count - 1].Location) + "\\" + fileContinuation[threadActivity.Count - 1].FileName + ".part" + (contFile + 1).ToString("0000") + ".7z";
                        if (File.Exists(testPath))
                        {
                            fsr.StartTransfer(fileContinuation[threadActivity.Count - 1].Location, o, this, uLogin, fileContinuation[threadActivity.Count - 1].Group, threadActivity.Count - 1, totalParts);
                        }
                        if (o == 0)
                        {
                            threadTransfer[o].Reset();
                        }
                        else
                        {
                            threadTransfer[o - 1].Set();
                            for (int u = o; u < threadTransfer.Count; u++)
                            {
                                threadTransfer[u].Reset();
                            }
                        }

                        for (int u = contFile + 1; u + threadCont < threadTransfer.Count(); u++)
                        {
                            string testContPath = Path.GetDirectoryName(fileContinuation[threadActivity.Count - 1].Location) + "\\" + fileContinuation[threadActivity.Count - 1].FileName + ".part" + (u + 1).ToString("0000") + ".7z";
                            string contPath = Path.GetDirectoryName(fileContinuation[threadActivity.Count - 1].Location) + "\\" + fileContinuation[threadActivity.Count - 1].FileName + ".part" + (u).ToString("0000") + ".7z";
                            if (File.Exists(testContPath))
                            {
                                fsr.StartTransfer(contPath, u, this, uLogin, fileContinuation[threadActivity.Count - 1].Group, threadActivity.Count - 1, totalParts);
                            }
                        }

                        foreach (ProgressBar pTemp in _ProgressBars)
                        {
                            if (pTemp.Name.StartsWith(ReplaceString(downloadStatusString) + "part") && String.Compare(pTemp.Name, ReplaceString(fileContinuation[threadActivity.Count - 1].FilePart)) < 0 && !pTemp.Name.Contains("Compression"))
                            {
                                pTemp.Value = 100;
                                pgBar_update(-2, -2, fileContinuation[threadActivity.Count - 1].FileName);
                            }
                        }
                        break;
                    }
                }
                else
                {
                    threadTransfer[o].Reset();
                }
            }
            threadCont = threadTransfer.Count() - 1;
            contFile = -1;
        }

        public void pgBar_update(long BytesRead, long BytesLength, string fileName)
        {
            foreach (ProgressBar temp in _ProgressBars)
            {
                if (BytesRead > -1 && BytesLength > -1)
                {
                    if (temp.Name == ReplaceString(Path.GetFileNameWithoutExtension(fileName)) + "_Transfer" || temp.Name == ReplaceString(Path.GetFileNameWithoutExtension(fileName)) + "_Download")
                    {
                        if (BytesLength != 0) temp.Value = (int)(BytesRead * 100 / BytesLength);
                        uploadProgressSaver(Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileName)), Path.GetFileNameWithoutExtension(fileName), BytesRead, temp.Value);
                        break;
                    }
                }
                else if (BytesRead == -2 && BytesRead == -2)
                {
                    if ((temp.Name == ReplaceString(fileName) + "_Transfer") || (temp.Name == ReplaceString(fileName) + "_Transfer_Status"))
                    {
                        temp.Value += 1;
                    }
                    else if ((temp.Name == ReplaceString(fileName) + "_Download") || (temp.Name == ReplaceString(fileName) + "_Download_Status"))
                    {
                        temp.Value += 1;
                    }
                }
                else
                {
                    if ((temp.Name == ReplaceString(Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileName))) + "_Transfer") || (temp.Name == ReplaceString(Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileName))) + "_Transfer_Status"))
                    {
                        temp.Value += 1;
                        if ((temp.Name == ReplaceString(Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileName))) + "_Transfer_Status") && temp.Value == temp.Maximum)
                        {
                            PictureBox pb = new PictureBox();
                            pb.Name = ReplaceString(Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(fileName)));
                            pb.ImageLocation = "upload";
                            cancel_Click(pb, null);
                            break;
                        }
                    }
                    else if (temp.Name == ReplaceString(Path.GetFileName(fileName)) + "_Download" || temp.Name == ReplaceString(Path.GetFileName(fileName)) + "_Download_Status")
                    {
                        temp.Value += 1;
                        if ((temp.Name == ReplaceString(Path.GetFileName(fileName)) + "_Download_Status") && temp.Value == temp.Maximum)
                        {
                            PictureBox pb = new PictureBox();
                            pb.Name = ReplaceString(Path.GetFileName(fileName));
                            pb.ImageLocation = "download";
                            cancel_Click(pb, null);
                            break;
                        }
                    }
                }
            }
        }

        private void AddStatus(int j)
        {
            Panel pnl = new Panel();
            PictureBox pct = new PictureBox();
            Label cellLabel = new Label();
            ProgressBar pgBar = new ProgressBar();
            ManualResetEvent _suspendEvent = new ManualResetEvent(true);
            threadActivity.Add(_suspendEvent);
            

            //Add Status
            tlpStatus.RowCount += 1;
            tlpStatus.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));

            //Add main file
            cellLabel = new Label();
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleLeft;
            if (j == 0)
            {
                cellLabel.Text = Path.GetFileName(trvLocal.SelectedNode.Text);
                _ActiveUpload.Add(cellLabel);
            }
            else
            {
                cellLabel.Text = Path.GetFileName(trvRemote.SelectedNode.Text);
                _ActiveDownload.Add(cellLabel);
            }
            tlpStatus.Controls.Add(cellLabel, 0, i - 1);

            //Add main file progress bars
            if (j == 0)
            {
                pgBar = new ProgressBar();
                pgBar.Dock = DockStyle.Fill;
                pgBar.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text)) + "_Compression_Status";
                pgBar.Maximum = m;
                _ProgressBars.Add(pgBar);
                tlpStatus.Controls.Add(pgBar, 1, i - 1);
            }
            else
            {
                //Compression n/a on transfer
                cellLabel = new Label();
                cellLabel.Text = @"N/A";
                cellLabel.Dock = DockStyle.Fill;
                cellLabel.TextAlign = ContentAlignment.MiddleCenter;
                tlpStatus.Controls.Add(cellLabel, 1, i - 1);
            }


            pgBar = new ProgressBar();
            pgBar.Dock = DockStyle.Fill;
            if (j == 0)
            {
                pgBar.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text)) + "_Transfer_Status";
            }
            else
            {
                pgBar.Name = ReplaceString(Path.GetFileName(trvRemote.SelectedNode.Text)) + "_Download_Status";
            }
            pgBar.Maximum = m;
            _ProgressBars.Add(pgBar);
            tlpStatus.Controls.Add(pgBar, 2, i - 1);

            //Add actions button
            pnl = new Panel();
            pnl.Dock = DockStyle.Fill;

            //Add close button
            pct = new PictureBox();
            pct.Dock = DockStyle.Right;
            pct.Image = (Image)Properties.Resources.remove_file;
            if (j == 0)
            {
                pct.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text));
            }
            else
            {
                pct.Name = ReplaceString(Path.GetFileName(trvRemote.SelectedNode.Text));
            }
            pct.Size = new System.Drawing.Size(17, 17);
            pct.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            pct.TabIndex = 0;
            pct.TabStop = false;
            pct.Click += new EventHandler(cancel_Click);
            pnl.Controls.Add(pct);

            int temp = threadActivity.Count - 1;

            //Add pause/resume buttom
            pct = new PictureBox();
            pct.Dock = DockStyle.Left;
            pct.Image = (Image)Properties.Resources.media_playback_pause;
            pct.Name = temp.ToString();
            pct.Tag = "Pause";
            pct.Size = new System.Drawing.Size(17, 17);
            pct.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            pct.TabIndex = 0;
            pct.TabStop = false;
            pct.Click += new EventHandler(play_Click);
            pnl.Controls.Add(pct);
            tlpStatus.Controls.Add(pnl, 3, i - 1);

            //Add main file notes
            cellLabel = new Label();
            cellLabel.Text = "SHOW MORE";
            cellLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            if (j == 0)
            {
                cellLabel.Name = ReplaceString(Path.GetFileName(trvLocal.SelectedNode.Text));
            }
            else
            {
                cellLabel.Name = ReplaceString(Path.GetFileName(trvRemote.SelectedNode.Text));
            }
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleLeft;
            cellLabel.Click += new EventHandler(OpenForm_Click);
            cellLabel.MouseHover += new System.EventHandler(mouse_Hover);
            cellLabel.MouseLeave += new System.EventHandler(this.btnsLeave);
            tlpStatus.Controls.Add(cellLabel, 4, i - 1);

            i++;
        }

        private void OpenForm_Click(object sender, EventArgs e)
        {
            Label lb = (Label)sender;
            foreach (TabPage tbPage in _HiddenPages)
            {
                if (tbPage.Name == lb.Name)
                {
                    tabControl1.TabPages.Add(tbPage);
                    tabControl1.SelectedTab = tbPage;
                    _HiddenPages.Remove(tbPage);
                    break;
                }
            }
        }

        private void play_Click(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            if (pb.Tag == "Pause")
            {
                pb.Image = (Image)Properties.Resources.media_playback_start;
                threadActivity[Int32.Parse(pb.Name)].Reset();
                pb.Tag = "Play";
            }
            else
            {
                pb.Image = (Image)Properties.Resources.media_playback_pause;
                threadActivity[Int32.Parse(pb.Name)].Set();
                pb.Tag = "Pause";
            }
        }

        private void cancel_Click(object sender, EventArgs e)
        {
            int found = 0;
            PictureBox pb = (PictureBox)sender;
            try
            {
                foreach (TabPage tpTemp in tabControl1.TabPages)
                {
                    if (tpTemp.Name == pb.Name)
                    {
                        DialogResult messageAlert = new DialogResult();
                        if (pb.ImageLocation == "upload")
                        {
                            messageAlert = customMessage("Confirm", "Upload Succeded", "File upload completed successfully. Removing temporary files...", "OK", null);
                        }
                        else if (pb.ImageLocation == "download")
                        {
                            messageAlert = customMessage("Confirm", "Download Succeded", "File download completed successfully. Removing temporary files...", "OK", null);
                        }
                        else
                        {
                            messageAlert = customMessage("Confirm", "Are you sure?", "Are you sure you want to cancel " + tpTemp.Text + "?", "Yes", "No");
                        }
                        if (messageAlert == DialogResult.Yes)
                        {
                            found = 1;
                            Stop_Transfer(tpTemp);
                            foreach (Label temp in _ActiveUpload)
                            {
                                if (ReplaceString(temp.Text) == pb.Name)
                                {
                                    _ActiveUpload.Remove(temp);
                                    break;
                                }
                            }
                            foreach (Label temp in _ActiveDownload)
                            {
                                if (ReplaceString(temp.Text) == pb.Name)
                                {
                                    _ActiveDownload.Remove(temp);
                                    break;
                                }
                            }
                            tabControl1.TabPages.Remove(tpTemp);
                            Thread.Sleep(1000);

                            if (Directory.Exists(Properties.Settings.Default.Temp + @"\hct\" + uLogin.Username + @"\Uploads\" + tpTemp.Text))
                            {
                                Directory.Delete(Properties.Settings.Default.Temp + @"\hct\" + uLogin.Username + @"\Uploads\" + tpTemp.Text, true);
                            }
                            else if(Directory.Exists(Properties.Settings.Default.Temp + @"\hct\" + uLogin.Username + @"\Downloads\" + tpTemp.Text))
                            {
                                Directory.Delete(Properties.Settings.Default.Temp + @"\hct\" + uLogin.Username + @"\Downloads\" + tpTemp.Text, true);
                            }
                            UpdateMessageBoard("Removed temporary files " + Path.GetFileName(tpTemp.Text) + ".");
                            i--;
                            break;
                        }
                    }
                }
                if (found == 0)
                {
                    foreach (TabPage tpTemp in _HiddenPages)
                    {
                        if (tpTemp.Name == pb.Name)
                        {
                            DialogResult messageAlert = new DialogResult();
                            if (pb.ImageLocation == "upload")
                            {
                                messageAlert = customMessage("Confirm", "Upload Succeded", "File upload completed successfully. Removing temporary files...", "OK", null);
                            }
                            else if (pb.ImageLocation == "download")
                            {
                                messageAlert = customMessage("Confirm", "Download Succeded", "File download completed successfully. Removing temporary files...", "OK", null);
                            }
                            else
                            {
                                messageAlert = customMessage("Confirm", "Are you sure?", "Are you sure you want to cancel " + tpTemp.Text + "?", "Yes", "No");
                            }
                            if (messageAlert == DialogResult.Yes)
                            {
                                Stop_Transfer(tpTemp);
                                foreach (Label temp in _ActiveUpload)
                                {
                                    if (ReplaceString(temp.Text) == pb.Name)
                                    {
                                        _ActiveUpload.Remove(temp);
                                        break;
                                    }
                                }
                                foreach (Label temp in _ActiveDownload)
                                {
                                    if (ReplaceString(temp.Text) == pb.Name)
                                    {
                                        _ActiveDownload.Remove(temp);
                                        break;
                                    }
                                }
                                _HiddenPages.Remove(tpTemp);
                                Thread.Sleep(1000);
                                
                                if (Directory.Exists(Properties.Settings.Default.Temp + @"\hct\" + uLogin.Username + @"\Uploads\" + tpTemp.Text))
                                {
                                    Directory.Delete(Properties.Settings.Default.Temp + @"\hct\" + uLogin.Username + @"\Uploads\" + tpTemp.Text, true);
                                }
                                else if (Directory.Exists(Properties.Settings.Default.Temp + @"\hct\" + uLogin.Username + @"\Downloads\" + tpTemp.Text))
                                {
                                    Directory.Delete(Properties.Settings.Default.Temp + @"\hct\" + uLogin.Username + @"\Downloads\" + tpTemp.Text, true);
                                }
                                UpdateMessageBoard("Removed temporary file " + Path.GetFileName(tpTemp.Text) + ".");
                                i--;
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorReport(ex.Message.ToString());
            }                
        }

        private void Stop_Transfer(TabPage tbp)
        {
            foreach (Thread temp in threadStore.ToList())
            {
                if (temp.Name.Contains(tbp.Name))
                {
                    temp.Abort();
                    foreach (ProgressBar pgtemp in _ProgressBars.ToList())
                    {
                        if (pgtemp.Name.Contains(ReplaceString(tbp.Text)))
                        {
                            _ProgressBars.Remove(pgtemp);
                        }
                    }
                    foreach (FileStatus fcTemp in fileContinuation.ToList())
                    {
                        if (ReplaceString(fcTemp.FileName).Contains(tbp.Name))
                        {
                            fileContinuation.Remove(fcTemp);
                        }
                    }
                    threadStore.Remove(temp);
                }
            }
            foreach (Control c in tlpStatus.Controls)
            {
                if (c.Name == tbp.Name)
                {
                    RemoveRow(tlpStatus, tlpStatus.GetRow(c));
                    break;
                }
            }
        }

        private void RemoveRow(TableLayoutPanel panel, int rowIndex)
        {
            panel.RowStyles.RemoveAt(rowIndex);

            for (int columnIndex = 0; columnIndex < panel.ColumnCount; columnIndex++)
            {
                var control = panel.GetControlFromPosition(columnIndex, rowIndex);
                panel.Controls.Remove(control);
            }

            for (int i = rowIndex + 1; i < panel.RowCount; i++)
            {
                for (int columnIndex = 0; columnIndex < panel.ColumnCount; columnIndex++)
                {
                    var control = panel.GetControlFromPosition(columnIndex, i);
                    if (control != null)
                    {
                        panel.SetRow(control, i - 1);
                    }
                }
            }
            panel.RowCount--;
        }

        private void close_Click(object sender, EventArgs e)
        {
            _HiddenPages.Add(tabControl1.SelectedTab);
            tabControl1.TabPages.RemoveAt(tabControl1.SelectedIndex);
            tabControl1.SelectedIndex = 1;
        }

        public string ReplaceString(string name)
        {
            string pattern = " *[ \\~#%&*{}/:<>?|\"-.]+ *";
            string replacement = "";

            Regex regEx = new Regex(pattern);
            string sanitized = regEx.Replace(name, replacement);
            return sanitized;
        }

        public void UpdateCompression(string name)
        {
            foreach (ProgressBar temp in _ProgressBars)
            {
                if (temp.Name == name)
                {
                    temp.Value += 1;
                }
            }
        }

        public void UpdateTransfer(string name, int value, int total)
        {
            foreach (ProgressBar temp in _ProgressBars)
            {
                if (temp.Name == name)
                {
                    if (total != 0)
                    {
                        temp.Maximum = total;
                    }
                    temp.Value = value;
                }
            }
        }

        public void UpdateMessageBoard(string name)
        {
            txtMessages.AppendText(Environment.NewLine + " - " + name);
        }

        public DialogResult customMessage(string title, string heading, string message, string buttonYes, string buttonNo)
        {
            CustomMessage cMessage = new CustomMessage();
            cMessage.Text = title;
            cMessage.lblMessage.Text = message;
            cMessage.lblTitle.Text = heading;
            cMessage.btnYes.Text = buttonYes;
            if (buttonNo != null)
            {
                cMessage.btnNo.Text = buttonNo;
            }
            else
            {
                cMessage.btnNo.Visible = false;
            }
            return cMessage.ShowDialog();
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            try
            {
                int notElement = 0;
                foreach (TreeNode temp in AdminTreeNodes)
                {
                    if (temp.Text == trvRemote.SelectedNode.Text)
                    {
                        notElement = 1;
                    }
                }
                if (trvRemote.SelectedNode.Parent != null && notElement == 0)
                {
                    bool active = false;
                    foreach (Label checkLabel in _ActiveDownload)
                    {
                        if (checkLabel.Text == trvRemote.SelectedNode.Text)
                        {
                            active = true;
                        }
                    }
                    if (active == false)
                    {
                        CreateTabDownload(1);
                        //AddStatus(1);

                        FileSendRecieve fsr = new FileSendRecieve();
                        foreach (FileInformation fInfo in fim)
                        {
                            if (Path.GetFileName(fInfo.FileName) == trvRemote.SelectedNode.Text.ToString() && fInfo.GroupName == trvRemote.SelectedNode.Parent.Text.ToString())
                            {
                                fsr.StartDownload(fInfo.FileName, downloadArray, this, uLogin, threadActivity.Count - 1, trvRemote.SelectedNode.Parent.Text.ToString());
                                break;
                            }
                        }
                        UpdateMessageBoard("Started downloading file: " + trvRemote.SelectedNode.Text);
                        tabControl1.SelectedTab = tabStatus;
                    }
                    else
                    {
                        customMessage("Warning", "Download already in progress", "File: " + trvRemote.SelectedNode.Text + " is already being recieved from the server", "OK", null);
                    }
                }
                else
                {
                    customMessage("Error!!!", "Can't find selected file", "You must select a file to start downloading.", "OK", null);
                    UpdateMessageBoard("You must select a file to start downloading.");
                }
            }
            catch
            {
                customMessage("Error!!!", "Can't find selected file", "You must select a file to start downloading.", "OK", null);
                UpdateMessageBoard("You must select a file to start downloading.");
            }
        }

        private void CreateTabDownload(int k)
        {
            downloadArray = new List<string>();
            string tabProperties = Path.GetFileNameWithoutExtension(trvRemote.SelectedNode.Text);
            TabPage newPage = new System.Windows.Forms.TabPage();
            TableLayoutPanel tlpProperties = new TableLayoutPanel();
            Panel pnl = new Panel();
            PictureBox pct = new PictureBox();
            Label cellLabel = new Label();
            ProgressBar pgBar = new ProgressBar();

            newPage.BackColor = System.Drawing.SystemColors.GradientActiveCaption;
            newPage.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

            newPage.Controls.Add(tlpProperties); //Add table
            newPage.Controls.Add(pnl);

            newPage.Name = ReplaceString(Path.GetFileName(trvRemote.SelectedNode.Text)); //Set Page layout
            newPage.Padding = new System.Windows.Forms.Padding(3);
            newPage.Size = new System.Drawing.Size(613, 248);
            newPage.TabIndex = i;
            newPage.Text = tabProperties;
            _HiddenPages.Add(newPage);

            tlpProperties.ColumnCount = 4; //Create Columns
            tlpProperties.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 65F));
            tlpProperties.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
            tlpProperties.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 100F));
            tlpProperties.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 35F));

            long j = 0;

            foreach (FileInformation tempInfo in fim)
            {
                if (Path.GetFileName(tempInfo.FileName) == trvRemote.SelectedNode.Text)
                {
                    j = tempInfo.Size;
                    break;
                }
            }
            //j = 86302720;
            SplitJoinCompress sjc = new SplitJoinCompress();
            m = Convert.ToInt32(Math.Ceiling((double)j / sjc.FileParts() + 1));

            tlpProperties.RowCount = m + 2; //Create Rows
            for (int p = 0; p <= m; p++)
            {
                tlpProperties.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
            }

            //Set panel properties
            pnl.Dock = System.Windows.Forms.DockStyle.Top;
            pnl.Location = new System.Drawing.Point(3, 3);
            pnl.Size = new System.Drawing.Size(605, 21);
            pnl.Margin = new System.Windows.Forms.Padding(0, 3, 0, 3);
            tlpProperties.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Single;
            tlpProperties.AutoScroll = true;

            //Add close button
            pct = new PictureBox();
            pct.Dock = DockStyle.Right;
            pct.Image = (Image)Properties.Resources.delete;
            pct.Location = new System.Drawing.Point(580, 3);
            pct.Name = i.ToString();
            pct.Size = new System.Drawing.Size(21, 21);
            pct.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            pct.TabIndex = 0;
            pct.TabStop = false;
            pct.Click += new EventHandler(close_Click);
            pnl.Controls.Add(pct);

            //Add Panel
            newPage.Controls.Add(pnl);

            //Add labels
            cellLabel = new Label();
            cellLabel.Text = "File Names";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleCenter;
            tlpProperties.Controls.Add(cellLabel, 0, 0);

            cellLabel = new Label();
            cellLabel.Text = "Compression";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleCenter;
            tlpProperties.Controls.Add(cellLabel, 1, 0);

            cellLabel = new Label();
            cellLabel.Text = "Download";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleCenter;
            tlpProperties.Controls.Add(cellLabel, 2, 0);

            cellLabel = new Label();
            cellLabel.Text = "Notes";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleCenter;
            tlpProperties.Controls.Add(cellLabel, 3, 0);

            //Add main file
            cellLabel = new Label();
            cellLabel.Text = Path.GetFileName(trvRemote.SelectedNode.Text);
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleLeft;
            tlpProperties.Controls.Add(cellLabel, 0, 1);

            //Compression n/a on transfer
            cellLabel = new Label();
            cellLabel.Text = @"N/A";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleCenter;
            tlpProperties.Controls.Add(cellLabel, 1, 1);

            //Download progress bar
            pgBar = new ProgressBar();
            pgBar.Dock = DockStyle.Fill;
            pgBar.Name = ReplaceString(Path.GetFileName(trvRemote.SelectedNode.Text)) + "_Download";
            pgBar.Maximum = m;
            _ProgressBars.Add(pgBar);
            tlpProperties.Controls.Add(pgBar, 2, 1);

            //Add main file notes
            cellLabel = new Label();
            cellLabel.Name = ReplaceString(Path.GetFileName(trvRemote.SelectedNode.Text)) + "_Notes";
            cellLabel.Dock = DockStyle.Fill;
            cellLabel.TextAlign = ContentAlignment.MiddleLeft;
            tlpProperties.Controls.Add(cellLabel, 3, 1);

            downloadArray.Add(Path.GetFileName(trvRemote.SelectedNode.Text) + ".password" + ".7z");

            for (int p = 0; p < (m - 1); p++)
            {
                //Add sub file
                cellLabel = new Label();
                cellLabel.Text = "  - " + Path.GetFileName(trvRemote.SelectedNode.Text) + ".part" + p.ToString("0000");
                cellLabel.Dock = DockStyle.Fill;
                cellLabel.TextAlign = ContentAlignment.MiddleLeft;
                tlpProperties.Controls.Add(cellLabel, 0, p + 2);

                //Add sub file progress bars
                cellLabel = new Label();
                cellLabel.Text = @"N/A";
                cellLabel.Dock = DockStyle.Fill;
                cellLabel.TextAlign = ContentAlignment.MiddleCenter;
                tlpProperties.Controls.Add(cellLabel, 1, p + 2);

                pgBar = new ProgressBar();
                pgBar.Dock = DockStyle.Fill;
                pgBar.Name = ReplaceString(Path.GetFileName(trvRemote.SelectedNode.Text) + "part" + p.ToString("0000")) + "_Download";
                downloadArray.Add(Path.GetFileName(trvRemote.SelectedNode.Text) + ".part" + p.ToString("0000") + ".7z");
                _ProgressBars.Add(pgBar);
                tlpProperties.Controls.Add(pgBar, 2, p + 2);

                //Add sub file notes
                cellLabel = new Label();
                cellLabel.Name = ReplaceString(Path.GetFileName(trvRemote.SelectedNode.Text) + p.ToString("0000")) + "_Notes";
                cellLabel.Dock = DockStyle.Fill;
                cellLabel.TextAlign = ContentAlignment.MiddleLeft;
                tlpProperties.Controls.Add(cellLabel, 3, p + 2);
            }

            //Finish table properties
            tlpProperties.Dock = System.Windows.Forms.DockStyle.Fill;
            tlpProperties.Location = new System.Drawing.Point(3, 3);
            tlpProperties.Size = new System.Drawing.Size(607, 242);
            tlpProperties.TabIndex = 0;

            AddStatus(k);

            int y = downloadArray.Count();
            for (int o = 0; o < y; o++ )
            {
                if (contFile != -1)
                {
                    if (o == contFile + 1)
                    {
                        pgBar_update(-2, -2, fileContinuation[threadActivity.Count - 1].FileName);
                        foreach (ProgressBar pTemp in _ProgressBars)
                        {
                            if (pTemp.Name.StartsWith(ReplaceString(downloadStatusString) + "part") && String.Compare(pTemp.Name, ReplaceString(fileContinuation[threadActivity.Count - 1].FilePart)) < 0 && !pTemp.Name.Contains("Compression"))
                            {
                                pTemp.Value = 100;
                                pgBar_update(-2, -2, fileContinuation[threadActivity.Count - 1].FileName);
                            }
                        }
                        break;
                    }
                    downloadArray.RemoveAt(0);
                }
            }
            threadCont = threadTransfer.Count() - 1;
            contFile = -1;
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmSettings setSettings = new frmSettings(uLogin, this);
            setSettings.ShowDialog();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.Temp.Length == 0)
            {
                Properties.Settings.Default.Temp = Path.GetTempPath();
            }
            if (Properties.Settings.Default.ExtractLocation.Length == 0)
            {
                Properties.Settings.Default.ExtractLocation = Path.GetDirectoryName(Application.ExecutablePath) + @"\Downloads";
            }
            Properties.Settings.Default.Save();
            if (!Directory.Exists(Properties.Settings.Default.ExtractLocation))
            {
                Directory.CreateDirectory(Properties.Settings.Default.ExtractLocation);
            }

            cmbAdminTools.SelectedIndex = 0;

            uploadProgressLoader();
        }

        private void addNewUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmCreateUser createUser = new frmCreateUser();
            createUser.ShowDialog();
        }

        private void cmbAdminTools_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cmbAdminTools.SelectedIndex)
            {
                case 1:
                    //Create form to remove file from a group.
                    frmAdmin frmA = new frmAdmin(cmbAdminTools.SelectedIndex, fim, uLogin);
                    if (frmA.ShowDialog() == DialogResult.OK)
                    {
                        UpdateMessageBoard("File was deleted successfully.");
                        refreshRemoteFile();
                    }
                    break;
                case 2:
                    //Create form to add user to a group.
                    frmA = new frmAdmin(cmbAdminTools.SelectedIndex, uLogin);
                    if (frmA.ShowDialog() == DialogResult.OK)
                    {
                        UpdateMessageBoard("User was added successfully.");
                    }
                    break;
                case 3:
                    //Create form to delete a user from the group.
                    frmA = new frmAdmin(cmbAdminTools.SelectedIndex, uLogin);
                    if (frmA.ShowDialog() == DialogResult.OK)
                    {
                        UpdateMessageBoard("User was deleted successfully.");
                    }
                    break;
                case 4:
                    //Create form to create a group.
                    frmA = new frmAdmin(cmbAdminTools.SelectedIndex, uLogin);
                    if (frmA.ShowDialog() == DialogResult.OK)
                    {
                        UpdateMessageBoard("Group was added successfully.");
                        refreshRemoteFile();
                    }
                    break;
                case 5:
                    //Create form to delete a group.
                    frmA = new frmAdmin(cmbAdminTools.SelectedIndex, uLogin);
                    if (frmA.ShowDialog() == DialogResult.OK)
                    {
                        UpdateMessageBoard("Group was deleted successfully.");
                        refreshRemoteFile();
                    }
                    break;
                case 6:
                    //Create form to delete a group.
                    frmA = new frmAdmin(cmbAdminTools.SelectedIndex, uLogin);
                    if (frmA.ShowDialog() == DialogResult.OK)
                    {
                        UpdateMessageBoard("Users password was changed successfully.");
                    }
                    break;
            }
            //Set index back to 0
            cmbAdminTools.SelectedIndex = 0;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            //Call update method here. Not done, not able to implement
            refreshRemoteFile();
            trvRemote.ExpandAll();
        }

        private void btnRefresh_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
            ToolTip tt = new ToolTip();
            tt.SetToolTip(this.btnRefresh, "Refresh Files.");
        } 

        public void errorReport(string ex)
        {
            string activeDir = Environment.SpecialFolder.MyDocuments.ToString();
            string newPath = Path.Combine(activeDir, "Hermes Company Transfer");
            
            Directory.CreateDirectory(newPath);

            newPath = Path.Combine(newPath, "HCT error report.txt");
            if (!File.Exists(newPath))
            {
                using (File.Create(newPath)) { };
            }

            using (StreamWriter sw = File.AppendText(newPath))
            {
                sw.WriteLine(DateTime.Now + " --error--> " + ex);
                sw.Close();
            }

            UpdateMessageBoard("An error has been recorded and saved in " + newPath);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public void uploadProgressSaver(string fileName, string filePart, long position, int complete)
        {
            FileStatus tempFS = new FileStatus();
            tempFS.FileName = fileName;
            tempFS.FilePart = filePart;
            tempFS.Position = position;

            if (fileContinuation.Count == 0)
            {
                fileContinuation.Add(tempFS);
            }
            else
            {
                int active = 0;
                for (int i = 0; i < fileContinuation.Count; i++)
                {
                    if (fileContinuation[i].FileName == tempFS.FileName)
                    {
                        fileContinuation[i].FilePart = tempFS.FilePart;
                        fileContinuation[i].Position = tempFS.Position;
                        active = 1;
                        break;
                    }
                }
                if (active == 0)
                {
                    fileContinuation.Add(tempFS);
                }
            }
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (fileContinuation.Count != 0)
            {
                string fileSaveLocation = Properties.Settings.Default.Temp + "\\hct\\" + uLogin.Username + "\\Transfers\\saved.xml";
                string fileDirectory = Properties.Settings.Default.Temp + "\\hct\\" + uLogin.Username;
                Directory.CreateDirectory(Path.Combine(fileDirectory, "Transfers"));
                if (File.Exists(fileSaveLocation))
                {
                    File.Delete(fileSaveLocation);
                }

                XmlDocument doc = new XmlDocument();
                XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("FileContinuation"));
                XmlElement ell = (XmlElement)el.AppendChild(doc.CreateElement("Files"));
                foreach (FileStatus temp in fileContinuation.ToList())
                {
                    XmlElement elll = (XmlElement)ell.AppendChild(doc.CreateElement("File"));
                    elll.SetAttribute("FileName", temp.FileName);
                    elll.SetAttribute("Location", temp.Location);
                    elll.SetAttribute("FilePart", temp.FilePart);
                    elll.SetAttribute("FilePosition", temp.Position.ToString());
                    elll.SetAttribute("Group", temp.Group);
                    elll.SetAttribute("Tree", temp.Tree);
                }
                System.Diagnostics.Debug.WriteLine(doc.OuterXml);

                StreamWriter file = new StreamWriter(fileSaveLocation);
                doc.Save(file);
            }
            else
            {
                string fileSaveLocation = Properties.Settings.Default.Temp + "\\hct\\" + uLogin.Username + "\\Transfers\\saved.xml";
                if (File.Exists(fileSaveLocation))
                {
                    File.Delete(fileSaveLocation);
                }
            }
        }

        private void uploadProgressLoader()
        {
            string fileSaveLocation = Properties.Settings.Default.Temp + "\\hct\\" + uLogin.Username + "\\Transfers\\saved.xml";
            if (File.Exists(fileSaveLocation))
            {
                XmlDocument docReader = new XmlDocument();
                docReader.Load(fileSaveLocation);

                XmlNode fileListNode = docReader.SelectSingleNode("/FileContinuation/Files");
                XmlNodeList fileNodeList = fileListNode.SelectNodes("File");

                foreach (XmlNode fileTemp in fileNodeList)
                {
                    FileStatus fsStatus = new FileStatus();
                    fsStatus.FileName = fileTemp.Attributes.GetNamedItem("FileName").Value;
                    fsStatus.Location = fileTemp.Attributes.GetNamedItem("Location").Value;
                    fsStatus.FilePart = fileTemp.Attributes.GetNamedItem("FilePart").Value;
                    fsStatus.Position = long.Parse(fileTemp.Attributes.GetNamedItem("FilePosition").Value);
                    fsStatus.Group = fileTemp.Attributes.GetNamedItem("Group").Value;
                    fsStatus.Tree = fileTemp.Attributes.GetNamedItem("Tree").Value;
                    
                    fileContinuation.Add(fsStatus);
                }

                foreach (FileStatus fileTemp in fileContinuation.ToList())
                {
                    if (fileTemp.Tree == "trvLocal")
                    {
                        foreach (TreeNode temptree in trvLocal.Nodes)
                        {
                            foreach (TreeNode treeTemp in temptree.Nodes)
                            {
                                if (treeTemp.Text == fileTemp.FileName)
                                {
                                    string[] stringSeparators = new string[] { ".part", ".7z" };
                                    string[] result = fileContinuation[threadActivity.Count].FilePart.Split(stringSeparators, StringSplitOptions.None);
                                    contFile = Convert.ToInt32(result[1]);
                                    downloadStatusString = result[0];
                                    trvLocal.SelectedNode = treeTemp;
                                    foreach (TreeNode tTemp in AdminTreeNodes)
                                    {
                                        if (tTemp.Text == fileContinuation[threadActivity.Count].Group)
                                        {
                                            trvRemote.SelectedNode = tTemp;
                                            break;
                                        }
                                    }
                                    btnUpload_Click(null, null);
                                }
                            }
                        }
                    }
                    else if (fileTemp.Tree == "trvRemote")
                    {
                        foreach (TreeNode temptree in trvRemote.Nodes)
                        {
                            foreach(TreeNode treeTemp in temptree.Nodes)
                            {
                                if(treeTemp.Text == fileTemp.Group)
                                {
                                    string[] stringSeparators = new string[] { ".part", ".7z" };
                                    string[] result = fileContinuation[threadActivity.Count].FilePart.Split(stringSeparators, StringSplitOptions.None);
                                    contFile = Convert.ToInt32(result[1]);
                                    downloadStatusString = result[0];
                                    //trvRemote.SelectedNode = treeTemp;
                                    foreach (TreeNode tTemp in treeTemp.Nodes)
                                    {
                                        if (tTemp.Text == fileContinuation[threadActivity.Count].FileName)
                                        {
                                            trvRemote.SelectedNode = tTemp;
                                            break;
                                        }
                                    }
                                    btnDownload_Click(null, null);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}